<template lang="pug">
  .page
    .AccountsReceivableManage
      .form-shebao-title.font-16.font-weight 到款填写
      //- p.text-error {{supplementInsurances}}
      .search-form.mb-10
        Form.ivu-row.ivu-form-basic(ref="formData" :model="formData" :rules="rules" :label-width="96")
          FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'select'")
              //- 差额所属项目
              Select(v-if="item.model === 'balanceInsuranceName'" v-model="formData[item.model]" :placeholder="item.placeholder" clearable label-in-value @on-change="balanceInsuranceNameChange")
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item.code"
                  :key="index"
                ) {{ c_item.name }}
              //- 差额所属编号
              Select(v-else-if="item.model === 'balanceInsuranceCode'" v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item"
                  :key="index"
                ) {{ c_item }}
              Select(v-else-if="item.model === 'bankName'" v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item.label"
                  :key="index"
                ) {{ c_item.label }}
              //- Select(v-else :placeholder="item.placeholder")
              //-   Option(
              //-     v-for="(c_item, index) in arrListDown[item.options]"
              //-     :value="c_item.code"
              //-     :key="index"
              //-   ) {{ c_item.name }}

            //- 到款项目
            template(v-if="item.type === 'selectMultiple'")
              //- Select(v-model="formData[item.model]" :placeholder="item.placeholder" clearable multiple max-tag-count="2" label-in-value=true @on-change="insurancesChange")
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item.code"
                  :key="index"
                ) {{ c_item.name }}
              .follow-select-btn
                Poptip.w-100(placement="bottom")
                  Button.w-100.text-left {{supplementInsurancesTxt}}
                  .clearfix(slot="content")
                    Checkbox(:indeterminate="indeterminate" :value="checkAll" @on-change="handleCheckAll") 全部
                    CheckboxGroup(v-model="supplementInsurancesCodeArr" @on-change="checkAllGroupChange")
                      Checkbox.display-block(v-for="(c_item, c_index) in arrListDown[item.options]" :label="c_item.code" :key="c_index") {{c_item.name}}

            template(v-if="item.type === 'input'")
              Input(v-if="item.fn" v-model="formData[item.model]" :placeholder="item.placeholder" :disabled="item.isDisabled" @on-blur="listenCall(item.fn, formData[item.model])")
              Input(v-else v-model="formData[item.model]" :placeholder="item.placeholder" :disabled="item.isDisabled")

            template(v-if="item.type === 'datePicker'")
              DatePicker.w-100(v-if="item.model === 'date'" placeholder="请选择" type="month" format="yyyy-MM" :value="formData.date" @on-change="handleChangeDatePickerSplit(item.model, $event)" :disabled="item.isDisabled")
              DatePicker.w-100(v-else placeholder="请选择" type="date" format="yyyy-MM-dd" :value="formData.receiveDate" @on-change="handleChangeDatePicker(item.model, $event)")

            template(v-if="item.type === 'button'")
              Button(type="info" @click="postReceivableBill('formData')") 结算

      .form-shebao-title.font-16.font-weight 实到明细列表
      Table.hasTitle-table.beautiful-table(:columns="actualArrivalThead" :data="actualArrivalTableData" :stripe="true" ref="demoTable")
        .clearfix.pl-20.pr-20(slot="footer")
          Page(
            :total="actualArrivalTableComone.totalRows"
            @on-change="onChangePage('actualArrivalTableComone', $event)"
            @on-page-size-change="onpageSizeChange('actualArrivalTableComone', $event)"
            show-sizer
            show-total
            placement="top"
            prev-text="上一页"
            next-text="下一页"
            :page-size-opts="[10, 20, 30, 50, 100]"
          )

      .h30

      //- .form-shebao-title.font-16.font-weight 应到明细列表
      //- Table.hasTitle-table(border :columns="shouldArrivalThead" :data="shouldArrivalTableData" :stripe="true" ref="demoTable")
      //-   .clearfix.pl-20.pr-20(slot="footer")
      //-     span 共{{shouldArrivalTableComone.totalRows}}条
      //-     Page(
      //-       :total="shouldArrivalTableComone.totalRows"
      //-       @on-change="onChangePage('shouldArrivalTableComone', $event)"
      //-       @on-page-size-change="onpageSizeChange('shouldArrivalTableComone', $event)"
      //-       show-sizer
      //-       :page-size-opts="[10, 20, 30, 50, 100]"
      //-     )

      .clearfix.text-center.pt-20.pb-20
        Button(type="info" @click="goAccountsReceivableList") 返回应收账单
</template>

<script>
import { ActualArrivalThead, ShouldArrivalThead } from './ARtableHead.js'
import _cloneDeep from 'clone-deep'
import { ReceivableBillApi } from '@/api/ReceivableBill.api.js'
import { Common } from '@/utils/common.js'

export default {
  inject: ['reload'],

  name: '',

  data () {
    return {
      // companyId: '', // 公司ID
      // companyName: '', // 公司名称
      // companyCode: '', // 公司code
      // periodYear: '',
      // periodMonth: '',
      actualArrivalThead: _cloneDeep(ActualArrivalThead),
      shouldArrivalThead: _cloneDeep(ShouldArrivalThead),
      // tableData: [],
      actualArrivalTableData: [],
      shouldArrivalTableData: [],
      formData: {
        date: '',
        year: '',
        month: '',
        companyId: '', // 公司ID
        companyName: '', // 公司名称
        companyCode: '', // 公司code
        insurancesArr: '',
        receiveDate: this.$moment(new Date()).format('YYYY-MM-DD'),
        bankName: '',
        shouldArriveTotal: '',
        trueArriveTotal: '',
        balance: '',
        balanceInsuranceName: '',
        balanceInsuranceCode: '',
        remark: ''
      },
      formItem: [
        { type: 'datePicker', label: '费用月份：', placeholder: '请输入费用月份', prop: 'date', model: 'date', isDisabled: true, style: 'ivu-col-span-6' },
        { type: 'input', label: '客户名称：', placeholder: '请输入客户名称', prop: 'companyName', model: 'companyName', isDisabled: true, style: 'ivu-col-span-6' },
        { type: 'datePicker', label: '到款日期：', placeholder: '请选择到款日期', prop: 'receiveDate', model: 'receiveDate', style: 'ivu-col-span-6' },
        { type: 'select', label: '到款银行：', placeholder: '请选择到款银行', prop: 'bankName', model: 'bankName', style: 'ivu-col-span-6', options: 'BankName' },
        { type: 'input', label: '到款金额：', placeholder: '请输入到款金额', prop: 'trueArriveTotal', model: 'trueArriveTotal', style: 'ivu-col-span-6', fn: 'inputOnBlur' },
        { type: 'button', style: 'ivu-col-span-6' }
      ],
      rules: { // trigger: 'select'
        month: [
          // { required: true, message: '请选择费用月份' }
        ],
        companyName: [
          // { required: true, message: '请输入客户名称' }
        ],
        insurancesArr: [
          { required: true, message: '请选择到款项目' }
        ],
        receiveDate: [
          { required: true, message: '请选择实到日期' }
        ],
        bankName: [
          { required: true, message: '请选择到款银行' }
        ],
        shouldArriveTotal: [
          // { required: true, message: '请输入应到合计' }
        ],
        trueArriveTotal: [
          { required: true, message: '请输入实到合计' },
          { message: '请输入小数点后的数字并且不能超过2位', pattern: /(^([-]?)[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^([-]?)(0){1}$)|(^([-]?)[0-9]\.[0-9]([0-9])?$)/ }
          // { required: true, type: 'string', validator: Common.validatePatrnNo }
        ],
        balance: [
          { required: true, message: '请输入当期差额' }
        ]
        // balanceInsuranceName: [
        //   { required: true, message: '请选择差额所属项目' }
        // ],
        // balanceInsuranceCode: [
        //   { required: true, message: '请选择差额所属编号' }
        // ],
      },
      selectedEmployeeId: [], // 勾选的id集合,array格式
      selectedEmployeeArr: [], // 勾选的id, name数组集合
      actualArrivalTableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10, // 当前页面展示条数
        inServiceCount: 0, // 在职
        outServiceCount: 0 // 离职
      },
      shouldArrivalTableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10, // 当前页面展示条数
        inServiceCount: 0, // 在职
        outServiceCount: 0 // 离职
      },
      downLoadRul: '',
      arrListDown: {
        tempOps: [],
        BankName: [],
        receiveProgramNames: [],
        balanceProgramNames: [],
        balanceNos: []
      },
      datePickerDefault: new Date(), // 当前时间
      importExcel: {
        uploadLoading: false,
        progressPercent: 0,
        showProgress: false,
        showRemoveFile: false,
        file: null
      },
      supplementInsurancesArr: [], // 到款项目选择的数组
      supplementInsurancesCodeArr: [], // 到款项目选择的数组-code
      supplementInsurancesNameArr: [], // 到款项目选择的数组-name
      supplementInsurancesTxt: '请选择到款项目',
      currentBalanceInsuranceName: null, // 差额所属项目点击下拉时的选中项
      indeterminate: false,
      checkAll: false
    }
  },

  mounted () {
    Object.keys(this.formData).forEach(key => {
      // var self = this
      // this.formData.key = this.$route.query[key]
      // console.log('this.formData.key: ' + this.formData.key + ': ' + this.$route.query[key])
      // console.log(key)
      if (key !== 'receiveDate') {
        this.formData[key] = this.$route.query[key]
      }
    })
    console.log('this.formData: ', this.formData)

    // this.formData.companyName = this.$route.query.companyName
    var tempMonth = this.$route.query.month < 10 ? '0' + this.$route.query.month : this.$route.query.month
    this.formData.date = new Date(this.$route.query.year + '-' + tempMonth)

    // this.getEnum()

    this.getCompanyBankInfos()
    // this.getReceiveProgramNames()
    // this.getBalanceProgramNames()

    this.getReceivableBillDetailList()
    // this.getShouldArriveDetailList()
  },

  methods: {
    // 数据字典
    // getEnum () {
    //   let typeName = 'BankName'
    //   Common.getSelectValueList(typeName, this.arrListDown)
    // },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (tableComone, val) {
      // this.tableComone.pageIndex = val
      // this.query()
      if (tableComone === 'shouldArrivalTableComone') { // 应到明细列表
        this.shouldArrivalTableComone.pageIndex = val
        // this.getShouldArriveDetailList()
      } else {
        this.actualArrivalTableComone.pageIndex = val
        this.getReceivableBillDetailList()
      }
      console.log('tableComone: ', tableComone)
      console.log('val: ', val)
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (tableComone, val) {
      // this.tableComone.pageSize = val
      // this.query()
      console.log('tableComone: ', tableComone)
      console.log('val: ', val)
      if (tableComone === 'shouldArrivalTableComone') { // 应到明细列表
        this.shouldArrivalTableComone.pageIndex = 1
        this.shouldArrivalTableComone.pageSize = val
        // this.getShouldArriveDetailList()
      } else {
        this.actualArrivalTableComone.pageIndex = 1
        this.actualArrivalTableComone.pageSize = val
        this.getReceivableBillDetailList()
      }
    },

    // 监听所有调用的方法
    listenCall (methodsWords, param) {
      this[methodsWords](param)
    },

    // 表格选择操作
    handleOnSelectChange (value) {
      this.selectedEmployeeArr = value.map((item) => {
        return { id: item.id, name: item.name }
      })
      this.selectedEmployeeId = value.map((item) => {
        return item.id
      })
      console.log('列表勾选数组1', this.selectedEmployeeArr)
      console.log('列表勾选数组2', this.selectedEmployeeId)
    },

    // 日期选择(区分年月)
    handleChangeDatePickerSplit (model, value) {
      // this.formData[model] = value
      var timeArr = value.split('-')
      this.formData.year = timeArr[0]
      this.formData.month = timeArr[1]
    },

    // 日期选择
    handleChangeDatePicker (model, value) {
      this.formData[model] = value
    },

    // 回到应收账单页面
    goAccountsReceivableList () {
      this.$router.push({
        path: '/accountsReceivableNew',
        name: 'accountsReceivableNew',
        query: {}
      })
    },

    // 获取到款银行下拉列表
    async getCompanyBankInfos () {
      var arr = []
      let res = await ReceivableBillApi.getCompanyBankInfos()
      if (res.status === 200 && res.data.success === true) {
        res.data.data.map(item => {
          arr.push({ value: item.id, label: item.bankName })
        })
      }
      this.arrListDown.BankName = arr
    },

    // 获取到款项目
    // async getReceiveProgramNames () {
    //   let res = await ReceivableBillApi.getReceiveProgramNames()
    //   // console.log('获取到款项目res: ', res)
    //   if (res.status === 200 && res.data.success === true) {
    //     this.arrListDown.receiveProgramNames = res.data.data
    //     // this.arrListDown.receiveProgramNames.unshift({name: '全部', code: 'all'})
    //   }
    // },

    // 获取差额所属项目
    // async getBalanceProgramNames () {
    //   let res = await ReceivableBillApi.getBalanceProgramNames()
    //   // console.log('获取差额所属项目res: ', res)
    //   if (res.status === 200 && res.data.success === true) {
    //     this.arrListDown.balanceProgramNames = res.data.data
    //   }
    // },

    // 差额所属项目下拉改变
    balanceInsuranceNameChange (valueObj) {
      this.currentBalanceInsuranceName = valueObj
      console.log('差额所属项目下拉改变valueObj: ', valueObj)
      this.arrListDown.balanceProgramNames.map(item => {
        if (item.code === valueObj.value) {
          this.getBalanceNos(item.group)
        }
      })
    },

    // 到款项目
    // insurancesChange (values) {
    //   this.supplementInsurancesArr = values
    //   this.getShouldArriveTotal()
    // },

    // 获取应到合计
    async getShouldArriveTotal () {
      var params = {
        PeriodYear: this.formData.year,
        PeriodMonth: this.formData.month,
        CustomerGUID: this.formData.companyId,
        // InsuranceCodes: this.formData.insurancesArr
        InsuranceCodes: this.supplementInsurancesCodeArr
      }
      let res = await ReceivableBillApi.getShouldArriveTotal(params)
      console.log('获取应到合计res: ', res)
      if (res.status === 200 && res.data.success === true) {
        this.formData.shouldArriveTotal = res.data.data
      } else {
        this.formData.shouldArriveTotal = 0
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 获取差额所属编号
    async getBalanceNos (group) {
      var params = {
        companyID: this.formData.companyId,
        group: group,
        year: this.formData.year
      }
      let res = await ReceivableBillApi.getBalanceNos(params)
      // console.log('获取差额所属编号res: ', res)
      if (res.status === 200 && res.data.success === true) {
        this.arrListDown.balanceNos = res.data.data
      }
    },

    // 添加应付账单信息(结算)
    postReceivableBill (name) {
      var arr = []
      this.supplementInsurancesArr.map(item => {
        var temp = {
          name: item.label,
          code: item.value
        }
        arr.push(temp)
      })

      var params = {
        year: this.formData.year,
        month: this.formData.month,
        companyId: this.formData.companyId,
        companyName: this.formData.companyName,
        companyCode: this.formData.companyCode,
        insurances: arr,
        receiveDate: this.formData.receiveDate,
        bankName: this.formData.bankName,
        bankCode: this.formData.bankCode,
        shouldArriveTotal: this.formData.shouldArriveTotal,
        trueArriveTotal: this.formData.trueArriveTotal,
        balance: this.formData.balance,
        remark: this.formData.remark,
        balanceInsuranceName: this.currentBalanceInsuranceName ? this.currentBalanceInsuranceName.label : '',
        balanceInsuranceCode: this.currentBalanceInsuranceName ? this.currentBalanceInsuranceName.value : '',
        balanceInsuranceNo: this.formData.balanceInsuranceCode
      }
      console.log('🐟🐟🐟🐟 提交表单', params)
      this.$refs[name].validate((valid) => {
        if (valid) {
          ReceivableBillApi.postReceivableBill(params).then(res => {
            console.log('res: ', res)
            if (res.status === 200 && res.data.success === true) {
              this.$Message.success(res.data.message)
              this.reload()
            } else {
              this.$Message.error({
                content: res.data.message,
                duration: 10,
                closable: true
              })
            }
          })
        } else {
          this.$Message.warning('输入有误，请返回检查!')
        }
      })
    },

    // 获取实到明细列表
    async getReceivableBillDetailList () {
      var params = {
        PeriodYear: this.formData.year,
        PeriodMonth: this.formData.month,
        CustomerGUID: this.formData.companyId,
        PageIndex: this.actualArrivalTableComone.pageIndex,
        PageSize: this.actualArrivalTableComone.pageSize
      }
      let res = await ReceivableBillApi.getReceivableBillDetailList(params)
      // console.log('获取实到明细列表 res: ', res)
      if (res.status === 200 && res.data.success) {
        this.actualArrivalTableData = res.data.data
        this.actualArrivalTableComone.totalRows = res.data.totalRows
      } else {
        this.actualArrivalTableData = []
        // this.$Message.error({
        //   content: res.data.Message,
        //   // duration: 0,
        //   closable: true
        // })
      }
    },

    // 获取应到明细列表
    // async getShouldArriveDetailList () {
    //   var params = {
    //     PeriodYear: this.formData.year,
    //     PeriodMonth: this.formData.month,
    //     CustomerGUID: this.formData.companyId,
    //     PageIndex: this.shouldArrivalTableComone.pageIndex,
    //     PageSize: this.shouldArrivalTableComone.pageSize
    //   }
    //   let res = await ReceivableBillApi.getShouldArriveDetailList(params)
    //   // console.log('获取应到明细列表 res: ', res)
    //   if (res.status === 200 && res.data.success) {
    //     this.shouldArrivalTableData = res.data.data
    //     this.shouldArrivalTableComone.totalRows = res.data.totalRows
    //   } else {
    //     this.shouldArrivalTableData = []
    //     this.$Message.error({
    //       content: res.data.Message,
    //       // duration: 0,
    //       closable: true
    //     })
    //   }
    // },

    // 输入框失去焦点时触发
    inputOnBlur (value) {
      console.log('输入框失去焦点时触发 value: ', value)
      this.formData.balance = (value - this.formData.shouldArriveTotal).toFixed(2)
    },

    // 到款项目-全选
    handleCheckAll () {
      // this.checkAll = !this.checkAll
      // console.log('this.checkAll: ', this.checkAll)
      if (this.indeterminate) {
        this.checkAll = false
      } else {
        this.checkAll = !this.checkAll
      }
      this.indeterminate = false

      var tempSumArr = []
      var tempCodeArr = []
      var tempNameArr = []
      if (this.checkAll) {
        this.arrListDown.receiveProgramNames.map(item => {
          tempSumArr.push({ value: item.code, label: item.name }) // 包含code和name的对象数组
          tempCodeArr.push(item.code) // code数组
          tempNameArr.push(item.name) // name数组
        })
      } else {
        this.checkAll = false
      }
      this.supplementInsurancesArr = tempSumArr
      this.supplementInsurancesCodeArr = tempCodeArr
      this.supplementInsurancesNameArr = tempNameArr
      this.supplementInsurancesTxt = tempNameArr ? tempNameArr.join(',') : '请选择到款项目'
      this.formData.insurancesArr = tempCodeArr

      this.getShouldArriveTotal()
    },

    // 到款项目-单选
    checkAllGroupChange (data) {
      var tempSumArr = []
      var tempCodeArr = []
      var tempNameArr = []
      if (data.length === this.arrListDown.receiveProgramNames.length) {
        this.indeterminate = false
        this.checkAll = true
      } else if (data.length > 0) {
        this.indeterminate = true
        this.checkAll = false
      } else {
        this.indeterminate = false
        this.checkAll = false
      }
      this.arrListDown.receiveProgramNames.map(item => {
        if (data.indexOf(item.code) !== -1) {
          tempSumArr.push({ value: item.code, label: item.name }) // 包含code和name的对象数组
          tempCodeArr.push(item.code) // code数组
          tempNameArr.push(item.name) // name数组
        }
      })
      this.supplementInsurancesArr = tempSumArr
      this.supplementInsurancesCodeArr = tempCodeArr
      this.supplementInsurancesNameArr = tempNameArr
      this.supplementInsurancesTxt = tempNameArr ? tempNameArr.join(',') : '请选择到款项目'
      this.formData.insurancesArr = tempCodeArr

      this.getShouldArriveTotal()
    }
  } // methods end
}
</script>

<style lang="less" scoped>

</style>
